package com.example.demo.util;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.shiro.codec.Base64;
import org.apache.shiro.session.Session;

/**
 * 序列化工具类,序列化对应的{@link org.apache.shiro.session.Session}
 * <p>@author Henry.Y</p>
 * <p>@date 2019-08-30</p>
 */          
public class SerializableUtils {

	/**
	 * 序列化回话信息,将{@link org.apache.shiro.session.Session}转为字符串
	 * @param session
	 * @return
	 */
	public static String serialize(Session session){
		try{
			ByteArrayOutputStream bos= new ByteArrayOutputStream();
			ObjectOutputStream oos= new ObjectOutputStream(bos);
			oos.writeObject(session);
			return Base64.encodeToString(bos.toByteArray());
		}catch(Exception e){
			throw new RuntimeException("serialize session error",e);
		}
		
	}
	
	/**
	 * 反序列化会话信息,将session字符串转为{@link org.apache.shiro.session.Session}
	 * @param sessionStr
	 * @return
	 */
	public static Session deserialize(String sessionStr){
		try{
			ByteArrayInputStream bis= new ByteArrayInputStream(Base64.decode(sessionStr));
			ObjectInputStream ois= new ObjectInputStream(bis);
			return (Session)ois.readObject();
		}catch(Exception e){
			throw new RuntimeException("deserialize session error",e);
		}
	}
}
